package io.gitee.hchaojie.day05;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestSort {
    @Test
    public void test() {
        List<Student> students = new ArrayList<>();

        students.add(new Student("zhangsan", 18, "10001"));
        students.add(new Student("lisi", 30, "10002"));
        students.add(new Student("wangwu", 19, "10003"));
        students.add(new Student("zhaoliu", 15, "10004"));

        for (Student s : students) {
            System.out.println(s);
        }

        // 集合排序，需要指定一个比较器
        Collections.sort(students, new Comparator<Student>() {
            // o1 > o2 => 正数
            // o1 == o2 => 0
            // o2 < o2 => 负数
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge() - o2.getAge();
            }
        });
        
        System.out.println("##########");
        
        for (Student s : students) {
            System.out.println(s);
        }
    }

    // 根据名字字母序排
    @Test
    public void testComparable() {
        List<Student> students = new ArrayList<>();

        students.add(new Student("zhangsan", 18, "10001"));
        students.add(new Student("lisi", 30, "10002"));
        students.add(new Student("wangwu", 19, "10003"));
        students.add(new Student("zhaoliu", 15, "10004"));

        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        
        for (Student s : students) {
            System.out.println(s);
        }
    }

    // 如果list集合里面的元素，实现了Comparable接口，(Comparable => 定义比较规则)
    // Collections.sort就会按照元素定义的比较规则进行排序
    @Test
    public void testString() {
        List<String> list = new ArrayList<>();
        
        list.add("zhangsan");
        list.add("lisi");
        list.add("wangwu");
        list.add("zhaoliu");
        
        Collections.sort(list);
        
        for (String s : list) {
            System.out.println(s);
        }
    }

    @Test
    public void testComparable2() {
        List<Student> students = new ArrayList<>();

        students.add(new Student("zhangsan", 18, "10001"));
        students.add(new Student("lisi", 30, "10002"));
        students.add(new Student("wangwu", 19, "10003"));
        students.add(new Student("zhaoliu", 15, "10004"));

        Collections.sort(students);

        for (Student s : students) {
            System.out.println(s);
        }
    }
}
